package car_test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

public class mr_monthly_sales_ratio {

    public static class MyMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {
        private final static DoubleWritable saleValue = new DoubleWritable();
        private Text monthKey = new Text();

        @Override
        public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            // 处理中文字符
            String line = new String(value.getBytes(), 0, value.getLength(), "GBK");
            // 使用正则表达式分割字段
            String[] strs = line.trim().split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", -1);

            if (strs != null && strs.length >= 12) {
                try {
                    // 第二列为月份，第十二列为销量
                    String month = strs[1].trim();  // 月份字段（第2列）
                    double sales = Double.parseDouble(strs[11].trim());  // 销量字段（第12列）

                    // 过滤掉空值或无效月份
                    if (!month.isEmpty()) {
                        monthKey.set(month);
                        saleValue.set(sales);
                        context.write(monthKey, saleValue);  // 输出 <月份, 销量>
                    }
                } catch (NumberFormatException e) {
                    // 忽略无法解析为数字的销量字段
                }
            }
        }
    }

    public static class MyReducer extends Reducer<Text, DoubleWritable, Text, DoubleWritable> {
        private Map<String, Double> monthlySales = new HashMap<>();
        private double totalSales = 0.0;

        @Override
        public void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            double sum = 0.0;
            for (DoubleWritable val : values) {
                sum += val.get();
            }

            // 存储每月销量并更新总量
            monthlySales.put(key.toString(), sum);
            totalSales += sum;
        }

        @Override
        public void cleanup(Context context) throws IOException, InterruptedException {
            // 计算并输出每月销量占比
            for (Map.Entry<String, Double> entry : monthlySales.entrySet()) {
                double ratio = entry.getValue() / totalSales;
                context.write(new Text(entry.getKey()), new DoubleWritable(ratio));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        String namenode_ip = "192.168.128.130";
        String hdfs = "hdfs://" + namenode_ip + ":8020";

        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", hdfs);

        Job job = Job.getInstance(conf, "monthly sales ratio analysis");

        job.setJarByClass(mr_monthly_sales_ratio.class);
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DoubleWritable.class);
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        String dataDir = "/car/data.csv";
        String outputDir = "/Output/monthly_sales_ratio";

        Path inPath = new Path(hdfs + dataDir);
        Path outPath = new Path(hdfs + outputDir);

        FileInputFormat.addInputPath(job, inPath);
        FileOutputFormat.setOutputPath(job, outPath);

        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outPath)) {
            fs.delete(outPath, true);
        }

        System.out.println("Job: monthly sales ratio analysis is running...");
        boolean success = job.waitForCompletion(true);
        if (success) {
            System.out.println("Job succeeded!");
        } else {
            System.out.println("Job failed!");
            System.exit(1);
        }
    }
}
